<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/2
 * Time: 11:22
 */

namespace app\index\controller;


use app\common\controller\Frontend;
use app\common\utils\Constant;
use app\common\utils\PayNotifyCallBack;
use app\index\logic\AnswerLogic;
use app\index\logic\RedEnvelopeLogic;
use think\Loader;
use think\Log;

Loader::import('wxpay.WxPayJsApiPay');
Loader::import('wxpay.WxPayUnifiedOrder');
Loader::import('wxpay.WxPayNotify');

/**
 * 支付操作相关
 * Class Pay
 * @package app\index\controller
 */
class Pay extends Frontend
{
    /**
     * ajax发起挑战 生成订单信息
     * @return \think\response\Json
     */
    public function ajax_do_challenge(){
        $result = $this->check();
        if(!$result['success']){
            return $this->returnJson($result['msg'],$result['code']);
        }
        $standard_id = $this->request->post('standard_id');
        $is_visible = $this->request->post('is_visible',0);
        $logic = new RedEnvelopeLogic();
        $result = $logic->createRedEnvelopeAndOrder($standard_id,$is_visible,$result['user_id']);
        $code = Constant::CODE_ERROR;
        $msg = '';
        $data = [];
        switch ($result['status']){
            case 0:
                $msg = '发起挑战失败！';
                $data = $result['error'];
                break;
            case 1:
                $msg = '创建订单成功！';
                $code = Constant::CODE_SUCCESS;
                $rtn_data = $result['data'];
                $description = '发起挑战';
                $title = '发起挑战';
                $data = $this->makeWeChatPay($rtn_data['open_id'],$description,$title,$rtn_data['number'],$rtn_data['money']);
                $data['number'] = $rtn_data['number'];//订单编号
                $data['money'] = $rtn_data['money'];
                $data['red_envelope_id'] = $rtn_data['red_envelope_id'];//红包id
                break;
            case 2:
                $msg = $result['msg'];
                break;
        }
        return $this->returnJson($msg,$code,$data);
    }

    /**
     * ajax 答题
     * @return \think\response\Json
     */
    public function ajax_do_answer(){
        $result = $this->check();
        if(!$result['success']){
            return $this->returnJson($result['msg'],$result['code']);
        }
        $red_envelope_id = $this->request->post('red_envelope_id');
        $user_id = $result['user_id'];
        $logic = new AnswerLogic();
        $result = $logic->doCreateAnswerLog($red_envelope_id,$result['user_id']);
        $code = Constant::CODE_ERROR;
        $msg = '';
        $data = [];
        switch ($result['status']){
            case 0:
                $msg = '答题失败！';
                $data = $result['error'];
                break;
            case 1:
                $rtn_data = $result['data'];
                if($rtn_data['is_need_pay']){
                    $msg = '创建订单成功！';
                    $description = '开始答题';
                    $title = '开始答题';
                    $data = $this->makeWeChatPay($rtn_data['open_id'],$description,$title,$rtn_data['number'],$rtn_data['money']);
                    $data['number'] = $rtn_data['number'];//订单编号
                }else{
                    $answer_log_id = $rtn_data['answer_log_id'];
                    pclose(popen("php /www/RedEnvelope/public/index.php /index/challenge/auto_end_answer/user_id/{$user_id}/answer_log_id/{$answer_log_id} &", 'r'));
                    $msg = '准备开始答题！';
                    $data = $rtn_data;
                }
                $data['is_need_pay'] = $rtn_data['is_need_pay'];//是否需要支付
                $data['answer_log_id'] = $rtn_data['answer_log_id'];//答题记录id
                $code = Constant::CODE_SUCCESS;
                break;
            case 2:
                $msg = $result['msg'];
                break;
        }
        return $this->returnJson($msg,$code,$data);
    }

    public function test(){
        if(!$this->request->isCli()){
            die();
        }
        $time = microtime();
        $count = 0;
        for ($i = 0 ;$i<1;$i++){
            $grade_array = $this->unique_rand(0,4,10);
            $grade = implode(',',$grade_array);
            $logic = new AnswerLogic();
            $topic_ids = $logic->getRandomTopicByGrade($grade,10);
            $topic_ids_arr = explode(',',$topic_ids);
            if(count($topic_ids_arr) < 10){
                $count ++;
            }

        }
        var_dump(microtime() - $time);
        var_dump($count);

    }


    private function unique_rand($min, $max, $num) {
        $count = 0;
        $return = array();
        while ($count < $num) {
            $return[] = mt_rand($min, $max);
            $count ++;
//            $return = array_flip(array_flip($return));
//            $count = count($return);
        }
        shuffle($return);
        return $return;
    }


    public function generateTopicIds($answer_log_id,$red_envelope_id){
        if(!$this->request->isCli()){
            die();
        }
        Log::write('answer_log_id:'.$answer_log_id);
        $answer_log = model('AnswerLog')
            ->where(array('id'=>$answer_log_id))
            ->field('topic_num')->find();
        $grade = model('RedEnvelope')->where(array('id'=>$red_envelope_id))->value('topic_grade');
        if($answer_log){
            $logic = new AnswerLogic();
            $topic_ids = $logic->getRandomTopicByGrade($grade,$answer_log['topic_num']);
            model('AnswerLog')
                ->where(array('id'=>$answer_log_id))->setField('topic_ids',$topic_ids);
        }
    }

    public function weChatPayRtn(){
        Log::write('begin notify');
        $notify = new PayNotifyCallBack();
        $notify->Handle(true);
    }

    /**
     * 生成微信支付参数
     * @param $openid
     * @param $description
     * @param $title
     * @param $order_number
     * @param $money
     * @return mixed
     */
    private function makeWeChatPay($openid,$description, $title, $order_number, $money)
    {

        $tools = new \JsApiPay();
        $openId = $openid;
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $description =mb_substr($description,0,20,'utf-8');
        $title =mb_substr($title,0,10,'utf-8');
        $input->SetBody($description);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_number);
        $input->SetTotal_fee($money*100);
//        $input->SetTotal_fee(1);
//        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($title);
        $url = 'http://'.$_SERVER['HTTP_HOST']."/index/pay/weChatPayRtn";
        $input->SetNotify_url($url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        //获取共享收货地址js函数参数
//        $editAddress = $tools->GetEditAddressParameters();
        $data['jsApiParameters'] = $jsApiParameters;
//        $data['editAddress'] = $editAddress;
        $data['money'] = $money;
        return $data;
    }
}